package com.wydpp.controller;

import com.wydpp.domain.Device;
import com.wydpp.gb28181.bean.R;
import com.wydpp.gb28181.bean.SipPlatform;
import com.wydpp.gb28181.commander.IFfmpegCommander;
import com.wydpp.gb28181.commander.SIPCommander;
import com.wydpp.repository.DeviceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/gb28181")
public class GB28181ClientController {

    @Autowired
    private SIPCommander sipCommander;

    @Autowired
    private SipPlatform sipPlatform;

    @Autowired
    private DeviceRepository deviceRepository;

    @Autowired
    private IFfmpegCommander ffmpegCommander;


    @PutMapping(path = "/register")
    public DeferredResult<R> register() {
        DeferredResult<R> result = new DeferredResult<>(1000 * 20L);
        result.onTimeout(() -> {
            result.setResult(R.fail("注册超时!"));
        });
        List<Device> devices = deviceRepository.findToBeRegisteredDevice();
        for (Device device : devices) {
            device.setNeedRegister(true);
            boolean sendResult = sipCommander.register(sipPlatform, device, eventResult -> {
                long time = System.currentTimeMillis();
                device.setRegisterTime(time);
                device.setKeepaliveTime(time);
                device.setOnline(true);
                result.setResult(R.ok("注册成功!"));
            });
            if (!sendResult) {
                result.setResult(R.fail("注册指令发送失败!"));
            }
        }
        return result;
    }

    // @PutMapping(path = "/unRegister")
    // public DeferredResult<R> unRegister() {
    //     DeferredResult<R> result = new DeferredResult<>(1000 * 5L);
    //     result.onTimeout(() -> {
    //         result.setResult(R.fail("注销超时!"));
    //     });
    //     sipDevice.setNeedRegister(false);
    //     boolean sendResult = sipCommander.unRegister(sipPlatform, sipDevice, eventResult -> {
    //         sipDevice.setOnline(false);
    //         // ffmpegCommander.closeAllStream();
    //         result.setResult(R.ok("设备注销成功!callId=" + eventResult.callId));
    //     });
    //     if (!sendResult) {
    //         result.setResult(R.fail("注销指令发送失败!"));
    //     }
    //     return result;
    // }

    @PutMapping(path = "/closePush")
    public R closePush(@RequestParam(name = "callId", required = false) String callId) {
        ffmpegCommander.closeStream(callId);
        return R.ok("停止推流成功");
    }

}
